package com.tplhk.drool.service.impl;

import cn.hutool.core.util.ReflectUtil;
import com.tplhk.drool.entity.PersonInfoEntity;
import com.tplhk.drool.entity.RuleBase;
import com.tplhk.drool.entity.RuleVo2Result;
import com.tplhk.drool.service.ClaimService;
import com.tplhk.drool.util.KieHelpUtil;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ClaimServiceImpl implements ClaimService {

    @Override
    public RuleBase getBaseByField(String fieldName, Object ParamValue) {
        return this.getBaseByField(fieldName, ParamValue, 0);
    }

    @Override
    public RuleBase getBaseByField(String fieldName, Object paramVaule, Integer defaultScore) {
        KieSession session = KieHelpUtil.kieHelper.build().newKieSession();
        PersonInfoEntity personInfoEntity = new PersonInfoEntity();
        ReflectUtil.invoke(personInfoEntity, "set" + this.captureName(fieldName), paramVaule);
        RuleVo2Result ruleVo2Result = new RuleVo2Result(defaultScore);
        session.setGlobal("ruleResult", ruleVo2Result);
        session.insert(personInfoEntity);
        session.fireAllRules();
        session.dispose();
        RuleBase subClass = ruleVo2Result.getSubClass(fieldName);
        if (Objects.isNull(subClass.getValue())) {
            subClass.setValue(paramVaule);
        }
        return subClass;
    }

    @Override
    public List<RuleBase> getBaseByField(String fieldName, List<Object> ListValue, Integer defaultScore) {
        List<RuleBase> result = new LinkedList<>();
        KieSession session = KieHelpUtil.kieHelper.build().newKieSession();
        ListValue.stream().filter(Objects::nonNull).map(paramVaule -> {
            PersonInfoEntity personInfoEntity = new PersonInfoEntity();
            ReflectUtil.invoke(personInfoEntity, "set" + this.captureName(fieldName), paramVaule);
            RuleVo2Result ruleVo2Result = new RuleVo2Result(defaultScore);
            session.setGlobal("ruleResult", ruleVo2Result);
            session.insert(personInfoEntity);
            session.fireAllRules();
            RuleBase subClass = ruleVo2Result.getSubClass(fieldName);
            if (Objects.isNull(subClass.getValue())) {
                subClass.setValue(paramVaule);
            }
            return subClass;
        }).forEach(result::add);
        session.dispose();
        return result;
    }

    /**
     * 将字符串的首字母转大写
     *
     * @param str 需要转换的字符串
     * @return
     */
    private String captureName(String str) {
        // 进行字母的ascii编码前移，效率要高于截取字符串进行转换的操作
        char[] cs = str.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }


}
